<h1>文章列表</h1>
<a href="/admin/articles/create" class="btn btn-success btn-sm mb-3">添加文章</a>
<a href="/admin/articles/export-ppt" class="btn btn-primary btn-sm mb-3">导出PPT</a>
<a href="/admin/articles/export-excel" class="btn btn-primary btn-sm mb-3">导出Excel</a>
<form method="get" action="/admin/articles" class="mb-3 mt-3">
  <div class="input-group">
    <input type="text" name="keyword" class="form-control" placeholder="请输入搜索关键字" value="{{keyword}}">
    <button class="btn btn-outline-secondary">搜索</button>
  </div>
</form>
<table class="table">
  <thead>
    <tr>
      <td>标题</td>
      <td>分类</td>
      <td>标签</td>
      <td>状态</td>
      <td>审核状态</td>
      <td>排序</td>
      <td>操作</td>
    </tr>
  </thead>
  <tbody>
    {{#each articles}}
    <tr>
      <td>{{this.title}}</td>
      <td>
        {{#each this.categories}}
        <span class="badge bg-secondary">{{this.name}}</span>
        {{/each}}
      </td>
      <td>
        {{#each this.tags}}
        <span class="badge bg-info text-dark">{{this.name}}</span>
        {{/each}}
      </td>
      <td><span class="status-toggle" data-id="{{this.id}}" data-status="{{this.status}}">
          {{#if this.status}}
          <i class="bi bi-check-circle-fill text-success"></i>
          {{else}}
          <i class="bi bi-x-circle-fill text-danger"></i>
          {{/if}}
        </span></td>
      <td>
        {{#if (eq this.state 'draft')}}<span class="badge bg-secondary">草稿</span>{{/if}}
        {{#if (eq this.state 'pending')}}<span class="badge bg-warning text-dark">待审核</span>{{/if}}
        {{#if (eq this.state 'published')}}<span class="badge bg-success">审核通过</span>{{/if}}
        {{#if (eq this.state 'rejected')}}<span class="badge bg-danger">审核不通过</span>{{/if}}
        {{#if (eq this.state 'withdrawn')}}<span class="badge bg-dark">已撤回</span>{{/if}}
      </td>
      <td>
        <span class="sort-text" data-id="{{this.id}}">
          {{this.sort}}
        </span>
        <input type="number" class="form-control sort-input d-none" style="width:50%" data-id="{{this.id}}"
          value="{{this.sort}}" />
      </td>
      <td>
        <a href="/admin/articles/{{this.id}}" class="btn btn-primary btn-sm">查看</a>
        <a href="/admin/articles/{{this.id}}/edit" class="btn btn-warning btn-sm">修改</a>
        <a class="btn btn-danger btn-sm" onclick="deleteArticle({{this.id}})">删除</a>
        {{#if (eq this.state 'draft')}}
        <button class="btn btn-warning btn-sm" onclick="submitForReview({{this.id}})">提交审核</button>
        {{/if}}
        {{#if (eq this.state 'pending')}}
        <button class="btn btn-warning btn-sm" onclick="approveaArticle({{this.id}})">审核通过</button>
        <button class="btn btn-danger btn-sm" data-bs-toggle="modal"
          data-bs-target="#rejectModal-{{this.id}}">审核不通过</button>
        <div class="modal fade" id="rejectModal-{{this.id}}" tabindex="-1">
          <div class="modal-dialog">
            <div class="modal-content">
              <div class="modal-header">
                <h5 class="modal-title">审核不通过</h5>
                <button type="button" class="btn-close" data-bs-dismiss="modal"></button>
              </div>
              <div class="modal-body">
                <div class="mb-3">
                  <label for="rejectionReason-{{this.id}}" class="form-label">不通过原因</label>
                  <textarea class="form-control" id="rejectionReason-{{this.id}}" name="rejectionReason"
                    rows="3"></textarea>
                </div>
              </div>
              <div class="modal-footer">
                <button type="button" class="btn btn-secodary" data-bs-dismiss="modal">关闭</button>
                <button type="button" class="btn btn-primary" onclick="rejectArticle({{this.id}})">提交</button>
              </div>
            </div>
          </div>
        </div>

        {{/if}}

        {{#if (eq this.state 'published')}}
        <button class="btn btn-danger btn-sm" onclick="withdrawnArticle({{this.id}})">撤回</button>
        {{/if}}
      </td>
    </tr>
    {{/each}}
  </tbody>
</table>
<nav>
  <ul class="pagination">
    <li class="page-item {{#if (eq page 1)}} disabled {{/if}}">
      <a class="page-link" href="?page={{dec page}}&keyword={{keyword}}&limit={{limit}}">上一页</a>
    </li>
    {{#each (range 1 pageCount)}}
    <li class="page-item {{#if (eq this ../page)}} active {{/if}}">
      <a class="page-link" href="?page={{this}}&keyword={{../keyword}}&limit={{../limit}}">{{this}}</a>
    </li>
    {{/each}}

    <li class="page-item {{#if (eq page pageCount)}}disabled{{/if}}">
      <a class="page-link" href="?page={{inc page}}&keyword={{keyword}}&limit={{limit}}">下一页</a>
    </li>
    <li class="page-item">
      <form method="get" action="/admin/articles" class="d-inline-block ms-3">
        <input type="hidden" name="keyword" value="{{keyword}}">
        <input type="hidden" name="page" value="{{page}}">
        <div class="input-group">
          <input type="number" name="limit" class="form-control" placeholder="每页的条数" value="{{limit}}" min="1">
          <button class="btn btn-outline-secondary" type="submit">设置每页的条数</button>
        </div>
      </form>
    </li>
  </ul>
</nav>
<script>
  function withdrawnArticle(id) {
    if (confirm('确定要撤回审核通过吗？')) {
      $.ajax({
        url: `/admin/articles/${id}/withdraw`,
        type: 'put',
        success: (data) => {
          if (data.success) {
            location.reload()
          }
        },
        error: function (error) {
          alert('撤回审核通过失败')
        }
      })
    }
  }
  function rejectArticle(id) {
    const rejectionReason = $(`#rejectionReason-${id}`).val()
    if (rejectionReason.trim() === '') {
      alert('请填写审核不通过的原因')
      return
    }
    $.ajax({
      url: `/admin/articles/${id}/reject`,
      type: 'put',
      contentType: 'application/json',
      data: JSON.stringify({ rejectionReason }),
      success: (data) => {
        if (data.success) {
          location.reload()
        }
      },
      error: function (error) {
        alert('审核不通过失败')
      }
    })
  }
  function approveaArticle(id) {
    if (confirm('确定要审核通过吗？')) {
      $.ajax({
        url: `/admin/articles/${id}/approve`,
        type: 'put',
        success: (data) => {
          if (data.success) {
            location.reload()
          }
        },
        error: function (error) {
          alert('审核通过失败')
        }
      })
    }
  }
  function submitForReview(id) {
    if (confirm('确定要提交审核吗？')) {
      $.ajax({
        url: `/admin/articles/${id}/submit`,
        type: 'put',
        success: (data) => {
          if (data.success) {
            location.reload()
          }
        },
        error: function (error) {
          alert('提交审核失败')
        }
      })
    }
  }
  function deleteArticle(id) {
    if (confirm('确定要删除吗')) {
      $.ajax({
        url: `/admin/articles/${id}`,
        type: 'delete',
        success: (data) => {
          if (data.success) {
            const params = new URLSearchParams(window.location.search)
            params.delete('page')
            params.append('page', 1)
            const query = params.toString()
            window.location = window.location.pathname + '?' + query
          }
        }
      })
    }
  }

  $(() => {
    $('.sort-text').on('dblclick', function () {
      const $this = $(this)
      const id = $this.data('id')
      $this.addClass('d-none')
      $(`.sort-input[data-id="${id}"]`).removeClass('d-none').focus()
    })
    $('.sort-input').on('blur', function () {
      const $this = $(this)
      const id = $this.data('id')
      const newSort = $this.val()
      $this.addClass('d-none')
      $(`.sort-input[data-id="${id}"]`).removeClass('d-none').text(newSort)

      $.ajax({
        url: `/admin/articles/${id}`,
        headers: {
          'accept': 'application/json'
        },
        contentType: 'application/json',
        type: 'put',
        data: JSON.stringify({ sort: +newSort }),
        success: (data) => {
          if (data.success) {
            location.reload()
          }
        }
      })
    })
    $('.status-toggle').on('click', function () {
      const $this = $(this)
      const id = $this.data('id')
      const currentStatus = $this.data('status')
      const newStatus = currentStatus == 1 ? 0 : 1
      $.ajax({
        url: `/admin/articles/${id}`,
        headers: {
          'accept': 'application/json'
        },
        contentType: 'application/json',
        type: 'put',
        data: JSON.stringify({ status: newStatus }),
        success: (data) => {
          if (data.success) {
            location.reload()
          }
        }
      })
    })
  })
</script>